package com.maserb.monitor.web.schoolConduct;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.jwQuestion.JwQuestionItemEntity;
import com.maserb.monitor.entity.schoolConduct.SchoolConductItemEntity;
import com.maserb.monitor.enums.JwEducationInfoIsReleasEnum;
import com.maserb.monitor.enums.JwEducationStautsEnum;
import com.maserb.monitor.enums.JwQuestionItemTypeEnum;
import com.maserb.monitor.enums.SchoolConductItemTypeEnum;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.jwQuestion.JwQuestionItemService;
import com.maserb.monitor.service.schoolConduct.SchoolConductItemService;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 操行细则
 */
@Controller
@RequestMapping("/schoolConductItem")
public class SchoolConductItemController {

    @Autowired
    SchoolConductItemService schoolConductItemService;

    @Autowired
    private IToolService toolService;

    @Autowired
    private JwOrgService orgService;


    @RequestMapping(value = {"/", "/index"})
    public ModelAndView getIndex(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("school_conduct/index");
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        JwOrgEntity orgEntity = orgService.findOne(user.getOrgId());
        int treeLevel = orgEntity.getTreeLevel();
        view.addObject("treeLevel",treeLevel);
        view.addObject("schoolId",user.getOrgId());
        view.addObject("user",user);
        return view;
    }

    @RequestMapping("/doListSchoolConductItem")
    @ResponseBody
    public PageResponseResult<SchoolConductItemEntity> doListSchoolConductItem(PageRequestParam page,String name ,String schoolId) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<SchoolConductItemEntity>>() {
            @Override
            public Page<SchoolConductItemEntity> invoke(PageRequest var1) throws Exception {
                Page<SchoolConductItemEntity> page = schoolConductItemService.findAll(var1,name,schoolId);
                for(SchoolConductItemEntity entity:page.getContent()){
                    entity.setCreateTime(toolService.formatYYMMDDHHMMSS(entity.getCreateTime()));
                }
                return page;
            }
        });
    }

    @RequestMapping("/getAddSchoolConductItem")
    public ModelAndView getAddSchoolConductItem() {
        ModelAndView result = new ModelAndView();
        SchoolConductItemTypeEnum[] type = SchoolConductItemTypeEnum.values();
        result.addObject("type",type);
        result.setViewName("school_conduct/addItem");
        return result;
    }

    @RequestMapping("/doAddSchoolConductItem")
    @ResponseBody
    public AjaxResult<Boolean> doAddSchoolConductItem(final HttpServletRequest request, SchoolConductItemEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                entity.setCreateTime(CreateTimeUtils.getCreateTime());
                HttpSession session = request.getSession(true);
                UserEntity userEntity = (UserEntity) session.getAttribute("user");
                entity.setCreateUser(userEntity.getId());
                String orgId = userEntity.getOrgId();
                if(!StringUtils.isEmptyOrWhitespace(orgId)){
                    JwOrgEntity orgEntity = orgService.findOne(orgId);
                    if(null!=orgEntity){
                        entity.setSchoolId(orgId);
                        entity.setSchoolName(orgEntity.getName());
                    }
                }
                schoolConductItemService.save(entity);
                return true;
            }
        });
    }

    @RequestMapping("/getUpdateItem/{id}")
    public ModelAndView getUpdateItem(@PathVariable final String id) {
        ModelAndView result = new ModelAndView();
        SchoolConductItemEntity entity = schoolConductItemService.findOne(id);
        result.setViewName("school_conduct/item_edit");
        SchoolConductItemTypeEnum[] type = SchoolConductItemTypeEnum.values();
        result.addObject("type",type);
        result.addObject("entity", entity);
        return result;
    }

    @RequestMapping("/doUpdateItem")
    @ResponseBody
    public AjaxResult<Boolean> doUpdateItem(final HttpServletRequest request, SchoolConductItemEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                SchoolConductItemEntity schoolConductItemEntity = schoolConductItemService.findOne(entity.getId());
                schoolConductItemEntity.setName(entity.getName());
                schoolConductItemEntity.setType(entity.getType());
                schoolConductItemEntity.setDescription(entity.getDescription());
                schoolConductItemEntity.setUpdateTime(CreateTimeUtils.getCreateTime());
                schoolConductItemEntity.setScore(entity.getScore());
                schoolConductItemService.save(schoolConductItemEntity);
                return true;
            }
        });
    }

    @RequestMapping("/doDeleteItem")
    @ResponseBody
    public AjaxResult<Boolean> doDeleteItem(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                schoolConductItemService.deleteAllByKeys(keys);
                return true;
            }
        });
    }

    /** 
    * @Description: 查看
    * @Param: [id] 
    * @return: org.springframework.web.servlet.ModelAndView 
    * @Author: Mr.Wang 
    * @Date: 2018/8/6
    */ 
    @RequestMapping("/getViewSchoolConduct/{schoolId}")
    public ModelAndView getViewSchoolConduct(@PathVariable final String schoolId) {
        ModelAndView result = new ModelAndView();
        JwOrgEntity orgEntity = orgService.findOne(schoolId);
        String schoolName = orgEntity.getName();
        List<SchoolConductItemEntity> itemEntityList = schoolConductItemService.findBySchoolId(schoolId);
        result.setViewName("school_conduct/view");
        result.addObject("schoolName", schoolName);
        result.addObject("itemList", itemEntityList);
        return result;
    }


    /**
    * @Description:  导出相应学校的操行细则
    * @Param: [response, userName, realName, orgId]
    * @return: void
    * @Author: Mr.Wang
    * @Date: 2018/8/6
    */
    @RequestMapping(value = "/exportConductItemLists")
    public void exportConductItemLists(HttpServletResponse response, final String name ,final String schoolId) {
        //模拟从数据库获取需要导出的数据
        List<SchoolConductItemEntity> itemLists = schoolConductItemService.findAll(name,schoolId);
        JwOrgEntity orgEntity = orgService.findOne(schoolId);
        String schoolName = orgEntity.getName();
        String excelName = "操行列表";
        if(!StringUtils.isEmptyOrWhitespace(schoolName)){
            excelName = schoolName+"的操行列表";
        }
        String fileName="";
        try{
            fileName  = excelName + System.currentTimeMillis()+".xls";
        }catch (Exception e){
            e.printStackTrace();
        }
        //导出操作
        ExcelExportUtils.exportExcel(itemLists, excelName, "", SchoolConductItemEntity.class, fileName, response);
    }

    //导入
    @RequestMapping("/goFileUpload/{schoolId}")
    public ModelAndView goFileUpload(@PathVariable final String schoolId) {
        ModelAndView result = new ModelAndView();
        result.setViewName("school_conduct/schoolConduct_import");
        result.addObject("schoolId", schoolId);
        return result;
    }


    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(final HttpServletRequest request,HttpServletResponse response, MultipartFile myfiles) throws IOException {
        /*HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String schoolId = user.getOrgId();
        String schoolName = "";
        if(!StringUtils.isEmptyOrWhitespace(schoolId)){
        }*/
        String schoolId =  request.getParameter("schoolId");
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedVerfiy(true);
        String resultStr = "导入成功";
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(myfiles.getInputStream(),SchoolConductItemEntity.class,params);
            List<SchoolConductItemEntity> list = result.getList();
            Sheet sheet = result.getWorkbook().getSheetAt(0);
            String sheetName = sheet.getSheetName();
            String title =sheet.getRow(0).getCell(0).getStringCellValue();
            if(null!=list && list.size()>0 && !StringUtils.isEmptyOrWhitespace(schoolId)){
                schoolConductItemService.saveImport(list,schoolId);
            }
        } catch (Exception e) {
            return "导入失败！";
        }
        return resultStr;
    }
}
